package db

import (
	"fmt"
	log "github.com/golang/glog"
	"github.com/garyburd/redigo/redis"
)

type Room struct {
	Appid int64
	Rid	  int64
	Name  string
	Avatar string
	Desc  string
	Members int64
}

func (room *Room) Save(conn redis.Conn) bool {
	//获取room ID
	key := fmt.Sprintf("%d_roomid", room.Appid)
	rid, err := redis.Int64(conn.Do("INCR", key))
	if err != nil {
		log.Error("redis INCR err: room.save", err)
		return false
	}
	
	room.Rid = rid
	
	key = fmt.Sprintf("%d_%d_roombase", room.Appid, room.Rid)
	_, err = conn.Do("HMSET", key, 
		"appid", fmt.Sprintf("%d", room.Appid), 
		"rid", fmt.Sprintf("%d", room.Rid), 
		"name", room.Name, 
		"avatar", room.Avatar, 
		"desc", room.Desc,
	)
	if err != nil {
		log.Error("redis HMSET err: room.save", err)
		return false
	}
	
	return true
}

func (room *Room) Get(conn redis.Conn, appid int64, rid int64) *Room {
	key := fmt.Sprintf("%d_%d_roombase", appid, rid)
	
	ret, err := redis.Strings(conn.Do("HMGET", key, "appid", "rid", "name", "avatar", "desc"))
	if err != nil {
		log.Error("redis HMGET err: room.get", err)
		return nil
	}
	
	key = fmt.Sprintf("%d_%d_roommembers", appid, rid)
	count, err := redis.Int64(conn.Do("SCARD", key))
	if err != nil {
		log.Error("redis SCARD err: room.get", err)
	}
	
	room.Appid = appid
	room.Rid = rid
	room.Name = ret[2]
	room.Avatar = ret[3]
	room.Desc = ret[4]
	room.Members = count
	
	return room
}

func AddRoomMember(conn redis.Conn, appid int64, rid int64, uid int64) bool {
	key := fmt.Sprintf("%d_%d_roommembers", appid, rid)
	
	_, err := conn.Do("SADD", key, uid)
	if err != nil {
		log.Error("redis SADD err: room.addmember", err)
		return false
	}
	
	return true
}

func RemoveRoomMember(conn redis.Conn, appid int64, rid int64, uid int64) bool {
	key := fmt.Sprintf("%d_%d_roommembers", appid, rid)
	
	_, err := conn.Do("SREM", key, uid)
	if err != nil {
		log.Error("redis SREM err: room.removemember", err)
		return false
	}
	
	return true
}

func RemoveRoom(conn redis.Conn, appid int64, rid int64) bool {
	key1 := fmt.Sprintf("%d_%d_roommembers", appid, rid)
	//删除聊天室信息
	key2 := fmt.Sprintf("%d_%d_roombase", appid, rid)
	_, err := conn.Do("DEL", key1, key2)
	if err != nil {
		log.Error("redis DEL err:room.remove", err)
		return false
	}
	
	return true
}

func GetRoomMembers(conn redis.Conn, appid int64, rid int64) []int{
	key := fmt.Sprintf("%d_%d_roommembers", appid, rid)
	ret, err := redis.Ints(conn.Do("SMEMBERS", key))
	if err != nil {
		log.Error("redis SMEMBERS err: room.getmembers", err)
		return nil
	}
	
	return ret
}